package com.example.myapplication8;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.myapplication8.databinding.FragmentHomeBinding;
import java.util.List;

public class HomeFragment extends Fragment {
    private FragmentHomeBinding binding;
    private MainViewModel viewModel;
    private MyAdapter adapter;
    private User user; // 接收用户信息

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 1. 获取MainActivity传递的User对象
        if (getActivity() != null) {
            Intent intent = getActivity().getIntent();
            user = (User) intent.getSerializableExtra("USER_INFO");
            // 显示欢迎信息（可选）
            if (user != null) {
                String welcomeMsg = "欢迎，" + user.getUsername() + "！你的兴趣：" + user.getSelectedInterests();
                Toast.makeText(getContext(), welcomeMsg, Toast.LENGTH_LONG).show();
            }
        }

        // 2. 原有逻辑（RecyclerView、ViewModel等）保持不变
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);
        adapter = new MyAdapter(
                item -> {
                    Intent intent = DetailActivity.newIntent(requireContext(), item);
                    startActivity(intent);
                },
                item -> viewModel.deleteItem(item.getId())
        );
        binding.rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.rvList.setAdapter(adapter);

        viewModel.getDataList().observe(getViewLifecycleOwner(), data -> {
            adapter.updateData(data);
        });

        binding.srlRefresh.setOnRefreshListener(() -> {
            viewModel.refreshData();
            binding.srlRefresh.setRefreshing(false);
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}